package org.dark.fund.configuration;

import org.dark.fund.interceptor.LoginFilter;
import org.dark.fund.interceptor.SpringMvcTraceFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

@Configuration
public class WebConfig implements WebMvcConfigurer {


    @Resource
    LoginFilter loginFilter;

    @Bean
    public SpringMvcTraceFilter getSpringMvcTraceFilter() {
        return new SpringMvcTraceFilter();
    }


    ;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getSpringMvcTraceFilter()).addPathPatterns("/**").order(100);
        registry.addInterceptor(loginFilter).addPathPatterns("/**").order(200);
    }

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:8081");
        String ALL = "*";
        config.addAllowedHeader(ALL);
        config.addAllowedMethod(ALL);
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }

}